//
//  JUFNHomeTBViewModel.swift
//  WiBoPM
//
//  Created by 陈俊峰 on 2017/1/10.
//  Copyright © 2017年 陈俊峰. All rights reserved.
//

import UIKit
import SDWebImage
class JUFNHomeTBViewModel: NSObject {

    //持有一个viewModel
//    var homeViewModel:JUFNHomeTBViewModel?
//       var userInfoStatuses : [JUFNUserStatus]?
    var homeCellModelS:[JUFNHomeCellModel] = [JUFNHomeCellModel]()
    
    ///方法要传进来一个参数,记录下拉控件是否是处于刷新中的状态,是否是下拉刷新
    func requestUserInfo(isPullUP:Bool,isSuccess:@escaping((Bool) -> ())) {
        let userInfoUrlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let access_token = JUFNAuthorViewModel.shared.userAcc?.access_token else {
            return
        }
        var pramrters = [
            "access_token":access_token
        ]
        let max_id = self.homeCellModelS.last?.userModel?.id
        if isPullUP {
            if max_id! > 0 {
                pramrters["max_id"] = "\(max_id! - 1)"
            }        }
        JUFNetworkingTools.shared.request(method: .GET, urlString: userInfoUrlString, prameters: pramrters) { (resp, error) in
            if error == nil {
                //说明请求成功
                let userInfo = resp as! [String:Any]
                //取出字典中的status
                let arrStatus = userInfo["statuses"] as! [[String:Any]]
                //创建临时变量数组
                var tempArr : [JUFNHomeCellModel] = [JUFNHomeCellModel]()
                for item in arrStatus {
                    let userSta = JUFNUserStatus()
                    let cellModel = JUFNHomeCellModel()
                    userSta.yy_modelSet(with: item)
                    cellModel.userModel = userSta
                    tempArr.append(cellModel)
                }
                if isPullUP {
                self.homeCellModelS = self.homeCellModelS + tempArr
                }else{
                    self.homeCellModelS = tempArr
                }
                self.handelTheSinglePic(cellModels: self.homeCellModelS, completeColsure: isSuccess)
            }else{
                isSuccess(false)
            }
        }
    }
    
    private func handelTheSinglePic(cellModels:[JUFNHomeCellModel],completeColsure:@escaping ((Bool) -> ())){
        ///为什么这里的数组个数是零还要返回成功
        if cellModels.count == 0 {
            completeColsure(true)
            return
        }
        let group = DispatchGroup()
        for cellmodel in cellModels{
           if cellmodel.images_url?.count == 1{
                //存入磁盘
            group.enter()
            SDWebImageManager.shared().downloadImage(with: cellmodel.images_url?.first?.picUrl, options: [], progress: nil, completed: { (_, _, _, _, _) in
                group.leave()
            })
                
            }
        }
        group.notify(queue: DispatchQueue.main) {
            completeColsure(true)
        }
    }
}
